package team.chess.dao;

import team.chess.util.Config;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


/**
 * @author Zxeao~Lenovo
 * @desrciption 登录函数，传入要登录的账号和密码
 * @return 登录成功返回真，否则为假（用户名或密码错误）
 * @throw 若碰到错误，会向外抛出
 */
public class Login {

    private final String account;
    private final String password;

    public Login(String account, String password) {
        this.account = account;

        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        this.password = new BigInteger(1, md.digest()).toString(16);
    }

    public boolean Login(){
        //加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //连接数据库
            Connection conn = DriverManager.getConnection(Config.JDBCURL, "zxeao", "123456");

            //通过连接对象 获得Statement 对象
            String sql = String.format("SELECT account FROM `account` WHERE password= '%s'",password);
            PreparedStatement statement  = conn.prepareStatement(sql);

            //执行SQL
            ResultSet res = statement.executeQuery();

            if (res.next()){
                System.out.println("登录成功");
                statement.close();
                conn.close();
                return true;
            }
        } catch (Exception e) {
            System.out.println("登录失败");
//            e.printStackTrace();
        }

        return false;
    }
}
